package com.dove.kuaizishareas.wificonnection;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import com.dove.kuaizishareas.R;
import com.dove.kuaizishareas.bean.Audio_file;
import com.dove.kuaizishareas.fragments.Audio;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;



public class ChooseConnect extends FragmentActivity {
	private ViewPager vpager;
	private Button send;
	private Context mContext;
	private Audio oneFragment;
	private List<Fragment> list = new ArrayList<Fragment>();
	private String Ip;
	private int number;
	private Socket ClientSocket = null;
	private List<Audio_file> sendList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_choosecontactlocal);
		mContext = this;
		
		initView();//初始化视图
		initData();
		
	}

	private void initData() {
		Ip = getIntent().getStringExtra("OtherIP");
		Log.i("dove", "ChooseConnet:要发送手机的ip:"+Ip);
		oneFragment = new Audio(this);
		list.add(oneFragment);
		ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
		vpager.setAdapter(adapter);
	}

	private void initView() {
		vpager = (ViewPager) this.findViewById(R.id.choose_ViewPager);
		send = (Button) this.findViewById(R.id.choose_send);
	}
	
	//send OnClickListener
	public void Sendonclick(View view){
		sendList = oneFragment.getSendList();
		number = sendList.size();
		Toast.makeText(mContext, "SendList:"+sendList.toString(), Toast.LENGTH_SHORT).show();
		
		if(sendList==null){
			sendList = new ArrayList<Audio_file>();
		}

		//单个文件发送
		File file = new File(sendList.get(0).getInfo());
		SendFile(file,0);
	}
	
	private void SendFile(File file,int i) {
		
		SendCommunicateThread sendinfo = new SendCommunicateThread(Ip, file.getName(), file, i);
		sendinfo.start();
		
	}

	class ViewPagerAdapter extends FragmentPagerAdapter{

		public ViewPagerAdapter(FragmentManager fm) {
			super(fm);
			// TODO Auto-generated constructor stub
		}

		@Override
		public Fragment getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}
		
	}
	
	@Override
	public void onBackPressed() {
		// 关闭datasocket
		Intent i = new Intent(ChooseConnect.this,WifiStart.class);
		startActivity(i);
		super.onBackPressed();
	}
	
	/**
	 * 向接收方发送信息的线程
	 * 
	 * @author yukunjin
	 * 
	 */
	class SendCommunicateThread extends Thread {

		private String IP = null;
		private OutputStream outStrm = null;
		private String sendinfo = null;
		private InputStream instrm = null;
		private int i;
		private File mfile;

		public SendCommunicateThread(String ip, String info, File mfile, int i) {
			IP = ip;
			sendinfo = info;
			this.i = i;
			this.mfile = mfile;
		}

		public void run() {
			try {
				// 建立和服务器的连接
				ClientSocket = new Socket(IP, WifiHelper.TCP_CommunicatePORT);
				Log.i("dove", "ChooseConnect:����շ������ļ���"+sendinfo.toString());
				// 阻塞运行
				outStrm = ClientSocket.getOutputStream();
				Log.i("dove", "ChooseConnect:fileName-"+sendinfo.toString());
				outStrm.write(sendinfo.getBytes());

				// 阻塞运行
				instrm = ClientSocket.getInputStream();
				byte flag = (byte) instrm.read();

				try {
					sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				int temp = 0x000000FF & ((int) flag);
				Message m = new Message();
				if(temp==0){//对方接收发送请求
					Byte type = (byte) i;
					WifiUserList.SendFileThread sft = new WifiUserList.SendFileThread(mfile, type, Ip,handler);
					sft.start();
					m.obj = "Send "+number+"...";
					handler.sendMessage(m);
				}else if(temp==1){//对方拒绝发送请求
					showdialog(mfile, i);
				}
				
				outStrm.close();
				instrm.close();
				ClientSocket.close();
				
			} catch (IOException e) {
				try {
					outStrm.close();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
	
	/***
	 *  获取接收方返回信息的线程
	 * 
	 * @author yukunjin
	 * 
	 */
	class GetCommunicateThread extends Thread {

		ServerSocket ss = null;
		Socket socket = null;
		File mfile;
		int i;
		
		public GetCommunicateThread(File mfile,int i) {
			super();
			this.mfile = mfile;
			this.i = i;
		}

		public void run() {
			try {
				ss = new ServerSocket(WifiHelper.TCP_CommunicatePORT);
				System.out.println("ResponseListening...");

				// accept阻塞直到被连接
				socket = ss.accept();
				System.out.println("ResponseThread Connected...");
				Log.i("dove", "ResponseThread Connected...");

				// 阻塞运行
				InputStream instrm = socket.getInputStream();
				byte flag = (byte) instrm.read();
				
				try {
					sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				int temp = 0x000000FF & ((int) flag);
				Log.i("dove", "ChooseConnect::响应数据temp==" + temp);
				Message m = new Message();
				if(temp==WifiHelper.TCP_SendFileOk){//对方接收文件完成
					if(number>0){
						number--;
						m.obj = "Send "+number+"...";
						handler.sendMessage(m);
					}else{
						m.obj = "Send End";
						handler.sendMessage(m);
					}
				}
				socket.close();
				ss.close();
				
			} catch (Exception e) {
				System.out.println("Connect请求线程出错");
				e.printStackTrace();
			}
		}
	}
	
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			if(msg.what==1010){//对方接收文件完成
				Message m = new Message();
				number--;
				if(number>0){
					m.obj = "Send "+number+"...";
					handler.sendMessage(m);
					handler.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							File file = new File(sendList.get(sendList.size()-number).getInfo());
							SendFile(file,number);
						}
					}, 1000);
					
				}else{
					oneFragment.getSendList().clear();
//					sendList = oneFragment.getSendList();
//					oneFragment.getSendList().removeAll(sendList);
//					oneFragment.setSendList(new ArrayList<Audio_file>());
					m.obj = "Send End";
					handler.sendMessage(m);
				}
			}else{
				String str = (String) msg.obj;
				if(send==null){
					send = (Button) ((Activity)mContext).findViewById(R.id.choose_send);
				}
				send.setText(str);
			}
		}
	};
	
	public Handler getHandler() {
		return handler;
	}
	public void setHandler(Handler handler) {
		this.handler = handler;
	}
	
	public void showdialog(final File mfile,final int i) {
		String content = "对方拒绝发送请求,是否重试?";
		new AlertDialog.Builder(ChooseConnect.this).setTitle("温馨提示")
		.setMessage(content).setIcon(
				android.R.drawable.ic_dialog_info)
		.setPositiveButton("重试", new OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				//重新发送文件
				Byte type = (byte) i;
				WifiUserList.SendFileThread sft = new WifiUserList.SendFileThread(mfile, type, Ip,handler);
				sft.start();
				Message m = new Message();
				m.obj = "Send "+number+"...";
				handler.sendMessage(m);
			}
		}).setNegativeButton("取消", new OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				Message m = new Message();
				m.obj = "Send "+number;
				handler.sendMessage(m);
			}
		}).create();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

}
